iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
Modern Web

React應用記錄誌系列 第 3

Day 03 實作練習 TodoList App Using useState

  • 分享至 

  • xImage
  •  

今天用useState()實作TodoList練習

https://ithelp.ithome.com.tw/upload/images/20220918/20139800qMJqu5BNmS.png
App.js

import React,{useState} from "react";
import Form from "./components/Form";
import TodoList from "./components/TodoList";

const App = () => {

   const [input,setInput] = useState("");
   const [todos,setTodos] = useState([]);

  return (
    <div className="container">
      <div className="app-box">
        <div>
          <h1 className='header'>TodoList</h1>
        </div>
        <div>
        <Form 
         input={input}
         setInput={setInput}
         todos={todos}
         setTodos={setTodos}
         />
        </div> 
        <div>
          <TodoList
          todos = {todos}
          setTodos = {setTodos}
          />
        </div>       
      </div>       
    </div>
  );
}

export default App;

Form.js

import React from 'react';
import {v4 as uuidv4} from "uuid";

const Form = ({input,setInput,todos,setTodos}) => {

    const onInputChange = (event) =>{
       setInput(event.target.value);
    };
     
    const onFormSubmit =(event)=>{
       event.preventDefault(); //停止執行事件的默認動作
       setTodos([...todos,{id:uuidv4(),title:input,completed:false}]);
       setInput("");
    };

  return (
    <form onSubmit = {onFormSubmit}>
       <input 
        type="text" 
        className='line-input' 
        placeholder='Enter a Todo...'
        value={input}
        require 
        onChange={onInputChange}

        />
       <button className='button-add' type='submit'>
           Add
       </button>
    </form>
  )
}

export default Form

TodoList.js

import React from 'react'

const TodoList = ({todos,setTodos}) => {

  return (
    <div>
      {todos.map((todo)=>(
        <li className='list-item' key={todo.id}>
           <input type="text"
             className='list'
             value={todo.title}
             onChange={(event)=>event.preventDefault()}                     
             />
        </li>
      ))}
    </div>
  )
}

export default TodoList


上一篇
Day02 React Hooks – useState
下一篇
Day04 React Hooks – useEffect
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言